﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace ECCSystem
{
    public partial class frm_Ext_Report_MailRecieved : Form
    {
        public frm_Ext_Report_MailRecieved()
        {
            InitializeComponent();
        }
        private DataSet objDS;
        private void btn_Export_Click(object sender, EventArgs e)
        {
          
            if(this.dateTimePicker_From.Value.CompareTo(this.dateTimePicker_To.Value) == 1 )
            {

            }

            var objBRReports = new ECCSystem.BizRule.ClsReports();
            objDS = (DataSet)objBRReports.GetMaiReceivedReport(this.dateTimePicker_From.Value
                                                                , this.dateTimePicker_To.Value);

            IDictionary<string, int[,]> _iDic = this.prepareDataForExcel(objDS.Tables[0]);

            this.CreateExcel(_iDic);

        }

        private IDictionary<string, int[,]> prepareDataForExcel(DataTable dt)
        {
            //+Prepare Data
            String recVDate = "";
            int[,] res = null;
            IDictionary<string, int[,]> _iDic = new Dictionary<string, int[,]>();

            for (var k = 0; k < dt.Rows.Count; k++)
            {
                var tmpTypes = new string[4];
                tmpTypes[0] = dt.Rows[k]["VDate"].ToString();
                tmpTypes[1] = dt.Rows[k]["VTime"].ToString();
                tmpTypes[2] = dt.Rows[k]["VType"].ToString();
                tmpTypes[3] = dt.Rows[k]["VCOUNT"].ToString();

                if (!recVDate.EndsWith(tmpTypes[0]))
                {
                    if (k != 0)
                        _iDic.Add(recVDate, this.SumRes(res));

                    res = this.GetInitRes();
                }

                recVDate = tmpTypes[0];

                int iTimeIdx =
                    //int.Parse(tmpTypes[1]) - 1;
                    int.Parse(tmpTypes[1]) - 8;
                iTimeIdx =
                iTimeIdx < 0 ? 24 + iTimeIdx : iTimeIdx;

                int iTypeIdx =
                    int.Parse(tmpTypes[2]) == 0 ? 2 : 1;//
                int iCount =
                    int.Parse(tmpTypes[3]);



                res[iTimeIdx, iTypeIdx] = int.Parse(tmpTypes[3]);

            }
            if (res != null)
                _iDic.Add(recVDate, this.SumRes(res));
            //-Prepare Data

            return _iDic;
        }

        private int[,] GetInitRes()
        {
            int[,] dst = new int[24, 3];

            for (int i = 0; i < 24; i++)
                for (int j = 0; j < 3; j++)
                    dst[i, j] = 0;

            return dst;
        }

        private int[,] SumRes(int[,] vSrc)
        {

            int vcnt = vSrc.Length/3;
            for (var i = 0; i < vcnt;i++ )
            {
                vSrc[i, 0] =
                    vSrc[i, 1] + vSrc[i, 2];
            }
            return vSrc;
        }

        //excel operation(open,fill,quit)
        private void CreateExcel(IDictionary<string, int[,]> vDic)
        {
            Excel.ApplicationClass objExlApp = new Excel.ApplicationClass();
            Excel.Workbook theWookbook = null;
            Excel.Worksheet theWookSheet = null;
            var objCommon = new ECCSystem.BizRule.ClsCommon();
            try
            {
                objExlApp.Visible = false;

                object objMissing = System.Reflection.Missing.Value;
                StringBuilder strSavePath = new StringBuilder();
                strSavePath.Append("C:\\ECCReport\\");
                //if strSavePath is not existing,create the path
                if (Directory.Exists(strSavePath.ToString()) == false)
                {
                    Directory.CreateDirectory(strSavePath.ToString());
                }

                StringBuilder strTemplatePath = new StringBuilder();
                //Excel template path
                strTemplatePath.Append(System.Windows.Forms.Application.StartupPath);
                strTemplatePath.Append("\\Ext\\ReportTemplate\\Ext_Report_MailRecieved.xls");
                //if this template is existing or not
                if (File.Exists(strTemplatePath.ToString()) == false)
                {
                    MessageBox.Show("レポートのテンプレートファイルが見つかりません。", "ECC Information");
                    //quit excel object
                    objCommon.QuitExcelApp(objExlApp, theWookbook, theWookSheet, null);
                    System.GC.Collect();
                    //this.btn_Export.Enabled = true;
                    return;
                }
                //open the excel template
                theWookbook = objExlApp.Workbooks.Open(strTemplatePath.ToString(), objMissing, objMissing, objMissing, objMissing, objMissing,
                                         objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing);
                //get the first sheet
                theWookSheet = (Excel.Worksheet)theWookbook.Worksheets[1];

                //fill data into excel


                int baseIdx = 0;
                Excel.Range rg;
                KeyValuePair<string,int[,]>? tmpData = null;
                foreach (var stringse in vDic)
                {


                    if(baseIdx > 0)
                    {
                        theWookSheet.Range["C2"].Value2 = stringse.Key;
                        theWookSheet.Range["C4:E27"].Value2 = stringse.Value;

                        theWookSheet.Range["C2:E27"].Copy();
                        rg = theWookSheet.Range["C2"].Next;
                        for (int i = 0; i < baseIdx * 3 - 1; i++)
                            rg = rg.Next;
                        rg.Select();
                        theWookSheet.Paste();
                    }else
                    {
                        tmpData = stringse;
                    }
                    baseIdx++;
                }

                if (tmpData.HasValue)
                {
                    theWookSheet.Range["C2"].Value2 = tmpData.Value.Key;
                    theWookSheet.Range["C4:E27"].Value2 = tmpData.Value.Value;
                }



                //set excel report save path and name
                //strSavePath.Append("PersonalMailReport" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString());
                //strSavePath.Append(DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".xls");
                strSavePath.Append("受信量" 
                                    + this.dateTimePicker_From.Value.Date.ToString("yyyy-MM-dd") 
                                    + "-" + this.dateTimePicker_To.Value.Date.ToString("yyyy-MM-dd"));


                if (File.Exists(strSavePath.ToString() + ".xls") == true)
                {
                    File.Delete(strSavePath.ToString() + ".xls");
                }

                //if the report has existed or not
                if (File.Exists(strSavePath.ToString()) == true)
                {
                    MessageBox.Show("このファイルがもう存在しました！", "ECC Information");
                    //quit excel object
                    objCommon.QuitExcelApp(objExlApp, theWookbook, theWookSheet, null);
                    System.GC.Collect();
                    //btnExcel.Enabled = true;
                    return;
                }

                //save the report
                theWookbook.SaveAs(strSavePath.ToString(), objMissing, objMissing, objMissing, objMissing, objMissing,
                    Excel.XlSaveAsAccessMode.xlNoChange, objMissing, objMissing, objMissing, objMissing);
                //prompt save success
                MessageBox.Show("操作成功しました。", "ECC Information");

                //quit excel object
                objCommon.QuitExcelApp(objExlApp, theWookbook, theWookSheet, null);
                System.GC.Collect();
                this.Close();
            }
            catch (Exception ex)
            {
                //quit excel object
                objCommon.QuitExcelApp(objExlApp, theWookbook, theWookSheet, null);
                System.GC.Collect();

                //MessageBox.Show(ex.ToString(), "ECC Catch Error");
                //btnExcel.Enabled = true;
            }
        }

    }
}
